package com.cac.demo.service.msTaskPackage;


import com.cac.demo.dao.gkLog.MsGkLogDao;
import com.cac.demo.dao.msConsole.MsConsoleDao;
import com.cac.demo.dao.msTaskPackage.MsTaskPackageDao;
import com.cac.demo.dao.pointPackageSort.PointPackageDao;
import com.cac.demo.entity.msTaskPackage.MsTaskPackageDTO;
import com.cac.demo.service.pointPackageSort.PointPackageSortService;
import com.cac.demo.util.CreateCommonLog;


import com.cac.demo.util.adapter.DaoException;
import com.cac.demo.util.adapter.QueryReqBean;
import com.cac.demo.util.adapter.QueryRespBean;
import com.cac.demo.util.adapter.ResponseMsg;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @program test-curd
 * @description 工作包分拣任务服务
 * @author: LSL
 * @create: 2022-08-29-14-16
 **/
@Service
@Slf4j
public class MsTaskPackageService {
    @Autowired
    private MsTaskPackageDao msTaskPackageDao;
    @Autowired
    private CreateCommonLog createCommonLog;
    @Autowired
    private MsConsoleDao msConsoleDao;
    @Autowired
    private MsGkLogDao msGkLogDao;
    @Autowired
    private PointPackageDao pointPackageDao;
    @Value("${pathProperty.isTest}")
    private boolean isTest;
    @Autowired
    private PointPackageSortService pointPackageSortService;

    /**
     * 配套计划条件查询
     *
     * @param queryReqBean
     * @return
     */
    public QueryRespBean<MsTaskPackageDTO> searchByPage(QueryReqBean<MsTaskPackageDTO> queryReqBean, Date startTime, Date endTime) {
        QueryRespBean<MsTaskPackageDTO> queryRespBean = new QueryRespBean<>();
        try {
            PageHelper.startPage(queryReqBean.getPageParameter());
            MsTaskPackageDTO searchParams = queryReqBean.getSearchParams();
            Page<MsTaskPackageDTO> dataList = msTaskPackageDao.searchMsTaskPackage(searchParams, startTime, endTime);
            queryRespBean.setResult(dataList);
            return queryRespBean;
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }
    }

    // 配套计划条件查询
    public QueryRespBean<MsTaskPackageDTO> searchByParams(QueryReqBean<MsTaskPackageDTO> queryReqBean, Date startTime, Date endTime) {
        QueryRespBean<MsTaskPackageDTO> queryRespBean = new QueryRespBean<>();
        try {
            PageHelper.startPage(queryReqBean.getPageParameter());
            MsTaskPackageDTO searchParams = queryReqBean.getSearchParams();
            Page<MsTaskPackageDTO> dataList = msTaskPackageDao.searchMsTaskPackageByPage(searchParams, startTime, endTime);
            queryRespBean.setResult(dataList);
            return queryRespBean;
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }
    }

    //分拣操作工作包任务查询
    public QueryRespBean<MsTaskPackageDTO> searchOperatePage(QueryReqBean<MsTaskPackageDTO> queryReqBean, Date startTime, Date endTime, String IP) {
        QueryRespBean<MsTaskPackageDTO> queryRespBean = new QueryRespBean<>();
        try {
            PageHelper.startPage(queryReqBean.getPageParameter());
            MsTaskPackageDTO searchParams = queryReqBean.getSearchParams();
            Page<MsTaskPackageDTO> dataList = msTaskPackageDao.searchOperatePage(searchParams, startTime, endTime, IP);
            queryRespBean.setResult(dataList);
            return queryRespBean;
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }
    }

    //工作包Ao包查询
    public QueryRespBean<MsTaskPackageDTO> searchPackageAoByPage(QueryReqBean<MsTaskPackageDTO> queryReqBean) {
        QueryRespBean<MsTaskPackageDTO> queryRespBean = new QueryRespBean<>();
        try {
            PageHelper.startPage(queryReqBean.getPageParameter());
            MsTaskPackageDTO searchParams = queryReqBean.getSearchParams();
            Page<MsTaskPackageDTO> dataList = msTaskPackageDao.searchPackageAoByPage(searchParams);
            queryRespBean.setResult(dataList);
            return queryRespBean;
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }
    }

    //已分拣工作包Ao包查询
    public QueryRespBean<MsTaskPackageDTO> searchSorted(QueryReqBean<MsTaskPackageDTO> queryReqBean) {
        QueryRespBean<MsTaskPackageDTO> queryRespBean = new QueryRespBean<>();
        try {
            PageHelper.startPage(queryReqBean.getPageParameter());
            MsTaskPackageDTO searchParams = queryReqBean.getSearchParams();
            Page<MsTaskPackageDTO> dataList = msTaskPackageDao.searchPackageAoByPageCompleted(searchParams);
            queryRespBean.setResult(dataList);
            return queryRespBean;
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }
    }

    //工艺更改查询
    public QueryRespBean<MsTaskPackageDTO> searchChangePackage(QueryReqBean<MsTaskPackageDTO> queryReqBean) {
        QueryRespBean<MsTaskPackageDTO> queryRespBean = new QueryRespBean<>();
        try {
            PageHelper.startPage(queryReqBean.getPageParameter());
            MsTaskPackageDTO searchParams = queryReqBean.getSearchParams();
            Page<MsTaskPackageDTO> dataList = msTaskPackageDao.searchPackageAoByPageChange(searchParams);
            queryRespBean.setResult(dataList);
            return queryRespBean;
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }
    }

    //工作包出库
    public List<HashMap> taskOut(HashMap hashMap) {
        return msTaskPackageDao.searchSslShelves(hashMap);
    }

    //配送工作包出库
    public List<HashMap> taskOutDelivery(HashMap hashMap) {
        return msTaskPackageDao.taskOutDelivery(hashMap);
    }

    //工作包物料信息查询
    @Transactional
    public QueryRespBean<HashMap> searchPackageMaterial(QueryReqBean<HashMap> queryReqBean, String orderBy, String Keywords) {
        QueryRespBean<HashMap> queryRespBean = new QueryRespBean<>();
        try {
            PageHelper.startPage(queryReqBean.getPageParameter());
            HashMap searchParams = queryReqBean.getSearchParams();
            Page<HashMap> dataList = msTaskPackageDao.searchPackageMaterial(searchParams, orderBy, Keywords);
            queryRespBean.setResult(dataList);
            return queryRespBean;
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }

    }

    //判断查询是否为空
    @Transactional
    public List<HashMap> searchPackageMaterial(HashMap searchParams, String orderBy, String Keywords) {
        try {
            List<HashMap> dataList = msTaskPackageDao.searchPackageMaterial(searchParams, orderBy, Keywords);
            return dataList;
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }

    }

    /*工作包物料信息新增*/
    @Transactional
    public int insertPackageMaterialInfo(HashMap map) {
        try {
            int count = msTaskPackageDao.insertPackageMaterialInfo(map);
            return count;
        } catch (Exception e) {
            throw new DaoException(e.getMessage(), e);
        }
    }

    /*工作包物料信息修改*/
    @Transactional
    public int updatePackageMaterial(HashMap map) {
        try {
            int count = msTaskPackageDao.updatePackageMaterial(map);
            if (count == 0) {
                throw new DaoException("修改数据失败");
            }
            return count;
        } catch (Exception e) {
            throw new DaoException(e.getMessage(), e);
        }
    }

    /*工作包物料信息删除*/
    @Transactional
    public int deletePackageMaterial(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new DaoException("删除失败！传入的参数主键为null");
        }
        try {
            //记录日志
            HashMap hashmap = msTaskPackageDao.searchPackageMaterialId(id);
            if (hashmap == null) {
                throw new DaoException("删除失败！对象不存在");
            }
//删除业务数据
            int count = msTaskPackageDao.deletePackageMaterial(id);
            return count;
        } catch (Exception e) {
            throw new DaoException(e.getMessage(), e);
        }
    }

    //查询配套任务数量
    public HashMap searchTaskCount() {
        HashMap result = msTaskPackageDao.searchTaskCount();
        return result;
    }

    //查询分拣台任务信息
    public HashMap searchSortTableCount(HashMap map) {
        HashMap result = msTaskPackageDao.searchSortTableCount(map);
        return result;
    }

    //查询当前分拣台对应工作包任务
    public HashMap searchCurrentPackage(String IP) {
        HashMap result = new HashMap();
        try {
            //获取工作包任务
            log.info(IP);
            List<HashMap> CurrentPackages = msTaskPackageDao.searchCurrentPackage(IP);
            for (int i = 0; i < CurrentPackages.size(); i++) {
                List<HashMap> CurrentAos = new ArrayList<>();
                //根据工作包任务编码，查询所属AO
                CurrentAos.addAll(msTaskPackageDao.searchCurrentAo(CurrentPackages.get(i).get("MSTASKPACKAGEID")));
                //将工作包下的所有ao放入CurrentPackages链表中对应的工作包。
                CurrentPackages.get(i).put("aoCodes", CurrentAos);
            }
            //工作包ao信息放入
            result.put("CurrentPackages", CurrentPackages);
            //当前是否存在任务
            int sortindTask = msGkLogDao.sortingTask(IP);
            if (sortindTask != 0) {
                //存在正在分拣的任务
                /**
                 * 处于输送线最前端的缓存箱，工作包托盘对应关系是否正确
                 * 工作包盘的工作包任务是否一致，ao对应是否一致
                 * 一致即返回对应的工作包id，ao编码，提供给前端进行高亮显示
                 * 不一致则提示页面进行更换工作包托盘，并提示下一个即将分拣的工作包id，ao编码
                 */
                //第一个工作包盘任务
           /*     List<HashMap> toolTask = msGkLogDao.sortFirstTool(IP);
                //第一个缓存箱任务
                List<HashMap> workBinTask = msGkLogDao.sortFirstWorkBin(IP);
                //判断工作包盘，缓存箱对应AO编码是否一样
                if (Integer.valueOf(toolTask.get(0).get("callPriority").toString())==Integer.valueOf(workBinTask.get(0).get("callPriority").toString())){
                    //工作包任务编码与缓存箱相同时。
                    //返回对应工作包id，ao编码给前端获取刷新页面数据。
                    result.put("nowPackageCode",toolTask.get(0).get("packageCode"));
                    result.put("nowAoCode",workBinTask.get(0).get("aoCode"));
                }else if (Integer.valueOf(toolTask.get(0).get("callPriority").toString())>Integer.valueOf(workBinTask.get(0).get("callPriority").toString())){
                    result.put("msg","当前缓存箱已操作！");
                    result.put("nowPackageCode",toolTask.get(0).get("packageCode"));
                    result.put("nowAoCode",workBinTask.get(1).get("aoCode"));
                } else {
                    result.put("msg","当前操作工作包盘已操作！");
                    result.put("nowPackageCode",toolTask.get(1).get("packageCode"));
                    result.put("nowAoCode",toolTask.get(0).get("aoCode"));
                    log.info("nowPackageCode"+toolTask.get(1).get("packageCode")+"+++++"+"nowAoCode"+workBinTask.get(0).get("aoCode"));
                }*/
            } else {
                //不存在正在分拣的任务
                result.put("msg", "不存在正在分拣的任务！");
                log.info("不存在正在分拣的任务");
            }

//        result.put("CurrentPackages",CurrentPackages);
//        result.put("CurrentAos",CurrentAosMap);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return result;
        }
    }

//    public List<HashMap> searchCurrentAo(String packageId){
//        List<HashMap> searchCurrentAo = msTaskPackageDao.searchCurrentAo(packageId);
//        return searchCurrentAo;
//    }

    //调用分拣叫箱存储过程
//    @Transactional
    public ResponseMsg callSortBoxSql(String IP) {
        ResponseMsg result = null;
        //根据ip查询当前分拣台下未分拣的托盘
        List<HashMap> toolCodeMap = msTaskPackageDao.searchToolCode(IP);
        if(toolCodeMap.size()>0){
            for(HashMap workbin : toolCodeMap){
                System.out.println("workbin"+workbin);
                result = pointPackageSortService.startPalletSortNewModel(workbin, IP);
                Integer retCode = Integer.valueOf(String.valueOf(result.getRetCode()));
                if( retCode== 201) {
                    return result;
                }
            }
        }else{
            return new ResponseMsg().setRetCode("201").setMessage("当前不存在未分拣的托盘!");
        }
//        try {
//            //0627 lqc查询当前第一个工作包
//            List<HashMap> rsl = msTaskPackageDao.searchCurrentPackage(IP);
//            String packageId = null;
//            HashMap pack = rsl.get(0);
//            packageId = (String) pack.get("MSTASKPACKAGEID");
//            HashMap map = new HashMap();
//            map.put("i_ip", IP);
//            map.put("i_package_id", packageId);
//            log.info("存储过程参数" + map.toString());
//            //声明分拣操作
//            map.put("func", "sort");
//            map.put("gzb_location", "");
//            map.put("hcx_location", "");
//            //获取调用存储过程返回结果 旧
////            msTaskPackageDao.callSortBoxSql(map);
//            //2023-06-27 lqc 新
//            if (isTest) {
//                pointPackageDao.callCreateTaskTest(map);
//            } else {
//                pointPackageDao.callCreateTask(map);
//            }
//
//            HashMap data = new HashMap();
//            //如果返回结果为执行成功
//            if (map.containsKey("o_Return_Int") && (Integer) map.get("o_Return_Int") == 0) {
//                //下发缓存箱出库指令
//                map.put("boxType", "WORKBIN");
//                //结束位置
//                map.put("endCode", "xyssj" + msConsoleDao.findStartCode(IP, (String) map.get("boxType")));
//                //首次下发命令标识符
//                map.put("firstCall", "firstCall");
//                //调用封装下发任务,接收返回
//                data.putAll(createCommonLog.callWCSInterface(map));
//                //下发工作包出库指令
//                map.replace("boxType", "TOOL");
//                //结束位置
//                map.put("endCode", "xyssj" + msConsoleDao.findStartCode(IP, (String) map.get("boxType")));
//                //调用封装下发任务
//                createCommonLog.callWCSInterface(map);
//                log.info(data.toString());
//                //查询该工作包任务所有AO
//                data.put("aoCodes", msTaskPackageDao.searchAllAoByPackage(data));
//                result.put("retCode", "200");
//                result.put("callWCSInterface", data);
//            } else {
//                result.put("retCode", "201");
//                result.put("callWCSInterface", map.get("o_Return_String"));
//            }
//            log.info("rrrrrrrrrrrrrrrrrrrrrrrrrr" + map.toString());
//        } catch (Exception e) {
//            e.printStackTrace();
//            result.put("retCode", "201");
//        }
        return result;
    }

    public List<HashMap> searchAoByPackageCode(HashMap map) {
        return msTaskPackageDao.searchAllAoByPackage(map);
    }

    //
    @Transactional
    public QueryRespBean<HashMap> searchMatchBill(QueryReqBean<HashMap> queryReqBean) {
        QueryRespBean<HashMap> queryRespBean = new QueryRespBean<>();
        try {
            PageHelper.startPage(queryReqBean.getPageParameter());
            HashMap searchParams = queryReqBean.getSearchParams();
            Page<HashMap> dataList = msTaskPackageDao.searchMatchBill(searchParams);
            queryRespBean.setResult(dataList);
            return queryRespBean;
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }
    }

    public QueryRespBean<HashMap> detailedAoInfo(QueryReqBean<HashMap> queryReqBean) {
        QueryRespBean<HashMap> queryRespBean = new QueryRespBean<>();
        List<HashMap> result = new ArrayList<>();
        try {
            String IP = null;
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            if (request.getHeader("x-forwarded-for") == null) {
                IP = request.getRemoteAddr();
            } else {
                IP = request.getHeader("x-forwarded-for");
            }
            //根据传入工作包主键id，查询AO信息，AO中托盘信息，托盘物料，对应初始缓存箱信息
            PageHelper.startPage(queryReqBean.getPageParameter());
            //ip
            result = msTaskPackageDao.toolUnpackInfo(IP);
            queryRespBean.setResult(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return queryRespBean;
        }
    }
}
